
interface IRenderOptions {
    onSwitched: any; // 点击之后发生
}

class Switch {
    hello(name: string): void {
        alert(`hello,${name}`);
    }
    render(options?: IRenderOptions): void {
        // 获取所有的switch按钮
        let switchs: NodeListOf<Element> = document.querySelectorAll("input[type=checkbox].kit-switch");
        // 循环处理
        for (let i: number = 0; i < switchs.length; i++) {
            // 获取当前的switch
            let cbx: HTMLInputElement = switchs[i] as HTMLInputElement;
            // 获取当前的选中状态
            let checked: boolean = cbx.checked;
            // 创建div标签
            let div: HTMLElement = document.createElement("div");
            // 给div标签添加className
            div.className = "kit-switched";
            // 创建span标签
            let span: HTMLElement = document.createElement("span");
            // 创建em标签
            let em: HTMLElement = document.createElement("em");
            // 设置相关参数
            if (checked) {
                span.className = "kit-switched-checked";
                em.innerText = "ON";
            } else {
                em.innerText = "OFF";
            }
            // 获取当前switch标签的父级节点
            let p: Node = cbx.parentNode;
            span.appendChild(em);
            div.appendChild(cbx);
            div.appendChild(span);
            p.appendChild(div);
            // 监听switch点击事件
            div.addEventListener("click", function (): void {
                let first: HTMLInputElement = this.childNodes[0] as HTMLInputElement;
                let span: HTMLSpanElement = this.childNodes[1] as HTMLSpanElement;
                let em: HTMLEmbedElement = span.childNodes[0] as HTMLEmbedElement;
                if (first.checked) {
                    span.className = "";
                    em.innerText = "OFF";
                    first.removeAttribute("checked");
                } else {
                    span.className = "kit-switched-checked";
                    em.innerText = "ON";
                    first.setAttribute("checked", "checked");
                }
                if (options !== undefined && typeof options.onSwitched === "function") {
                    // 触发回调函数
                    options.onSwitched({
                        elem: first,
                        othis: span,
                        parent: div
                    });
                }
            });
        }
    }
}

export default Switch;